package com.zn.filter;

import com.alibaba.fastjson.JSONObject;
import com.zn.util.AESEncrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/error")
public class GlobalErrorController extends AbstractErrorController {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalErrorController.class);
    @Autowired
    public GlobalErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }
    @Value("${aesKey}")
    private String aesKey;

    public static final Map<String, Object> ERROR_MAP = new LinkedHashMap<>();
    public static final Map<String, Object> FORBIDDEN_MAP = new LinkedHashMap<>();
    static {
        ERROR_MAP.put("resCode", "500");
        ERROR_MAP.put("msg", "网络拥堵,请重试");

        FORBIDDEN_MAP.put("resCode", "403");
        FORBIDDEN_MAP.put("msg", "Forbidden Error");
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 捕捉服务内500的异常
     * @param request
     * @return
     */
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity error(HttpServletRequest request){
        JSONObject respJson=new JSONObject();
        try {
            HttpStatus status = getStatus(request);
            LOGGER.info("错误状态码: " + status.value() + "\t请求路径: " + request.getRequestURI());
            if (status.is5xxServerError()) {
                JSONObject errorJson=new JSONObject(ERROR_MAP);
                String enctyptStr=AESEncrypt.aesEncrypt(errorJson.toString(), aesKey);
                respJson.put("enctyptData", enctyptStr);
                return ResponseEntity.ok(respJson);
            }
            JSONObject errorJson=new JSONObject(FORBIDDEN_MAP);
            String enctyptStr=AESEncrypt.aesEncrypt(errorJson.toString(), aesKey);
            respJson.put("enctyptData", enctyptStr);
            return ResponseEntity.ok(respJson);
        }catch (Exception e){
            LOGGER.error("error...", e);
            respJson.put("enctyptData", "CfdkMM2Bl3ToD7cS5efISngf9QUDYzWVzCWUs7AAsWD4mwahssLfOIdyKoVpBPcn");
            return ResponseEntity.ok(respJson);
        }
    }
}
